package com.nantai.jiafang.nantaijiafang.deviceManager.devicemanager;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.nantai.jiafang.nantaijiafang.R;
import com.nantai.jiafang.nantaijiafang.deviceManager.Adapter.CheckTaskAdapter;
import com.nantai.jiafang.nantaijiafang.deviceManager.Adapter.KeepTaskAdapter;
import com.nantai.jiafang.nantaijiafang.deviceManager.Adapter.NormalTaskAdapter;
import com.nantai.jiafang.nantaijiafang.deviceManager.bean.KeepTask;
import com.nantai.jiafang.nantaijiafang.deviceManager.bean.Patrol;
import com.nantai.jiafang.nantaijiafang.deviceManager.bean.Task;
import com.nantai.jiafang.nantaijiafang.deviceManager.http.Error;
import com.nantai.jiafang.nantaijiafang.deviceManager.http.HttpClient;
import com.nantai.jiafang.nantaijiafang.deviceManager.http.ResponseHandler;
import com.nantai.jiafang.nantaijiafang.deviceManager.utils.MessagePop;

import java.util.ArrayList;
import java.util.List;

import info.hoang8f.android.segmented.SegmentedGroup;
import okhttp3.ResponseBody;
import retrofit2.Call;

public class TaskActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {


   // @ViewInject(R.id.segmented2)
    SegmentedGroup mSegmented2;
   // @ViewInject(R.id.normal_btn)
    RadioButton mNormalBtn;
   // @ViewInject(R.id.task_btn)
    RadioButton mTaskBtn;
   // @ViewInject(R.id.norma_list)
    ListView mNormaList;
   // @ViewInject(R.id.task_list)
    ListView mTaskList;
   // @ViewInject(R.id.tv_toolbar_title)
    TextView mTvToolbarTitle;
   // @ViewInject(R.id.toolbar)
    Toolbar mToolbar;
   // @ViewInject(R.id.task_keep)
    RadioButton mTaskKeep;
   // @ViewInject(R.id.keep_list)
    ListView mKeepList;

    List mPatrolList = null;
    List mCheckList = null;
    List mKeepTaskList = null;
    NormalTaskAdapter mNormalTaskAdapter = null;
    KeepTaskAdapter mKeepTaskAdapter=null;

    private MaterialDialog showDialog = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task);

        /*====================================*/
        mSegmented2=(SegmentedGroup)findViewById(R.id.segmented2);
        mNormalBtn=(RadioButton)findViewById(R.id.normal_btn);
        mTaskBtn=(RadioButton)findViewById(R.id.task_btn);
        mNormaList=(ListView)findViewById(R.id.norma_list);
        mTaskList=(ListView)findViewById(R.id.task_list);
        mTvToolbarTitle=(TextView)findViewById(R.id.tv_toolbar_title);
        mToolbar=(Toolbar)findViewById(R.id.toolbar);
        mTaskKeep=(RadioButton)findViewById(R.id.task_keep);
        mKeepList=(ListView)findViewById(R.id.keep_list);

        /*====================================*/
        mTvToolbarTitle.setText("任务");
        mToolbar.setNavigationIcon(R.drawable.md_nav_back);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        mSegmented2.setOnCheckedChangeListener(this);
        mSegmented2.setTintColor(0xFF1b7ce8);
        showDialog = new MaterialDialog.Builder(TaskActivity.this)
                .content("正在请求数据")
                .progress(true, 0, false)
                .cancelable(false).build();
        mSegmented2.check(R.id.normal_btn);
        requestCheckTask();
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.normal_btn: {
                mNormaList.setVisibility(View.VISIBLE);
                mTaskList.setVisibility(View.GONE);
                mKeepList.setVisibility(View.GONE);
                if (mPatrolList == null) {
                    showDialog.show();
                    requestNormalTask();
                }
            }
            break;
            case R.id.task_btn: {
                mTaskList.setVisibility(View.VISIBLE);
                mNormaList.setVisibility(View.GONE);
                mKeepList.setVisibility(View.GONE);
                if (mCheckList == null) {
                    showDialog.show();
                    requestCheckTask();
                }
            }
            break;
            case R.id.task_keep: {
                mTaskList.setVisibility(View.GONE);
                mNormaList.setVisibility(View.GONE);
                mKeepList.setVisibility(View.VISIBLE);
                if (mKeepTaskList == null) {
                    showDialog.show();
                    requestKeepTask();
                }
            }
            break;
            default:
                // Nothing to do
        }
    }

    private void updateCheckList(List dataSource) {
        mCheckList = new ArrayList<>();
        mCheckList.addAll(dataSource);
        mTaskList.setAdapter(new CheckTaskAdapter(mCheckList, this));
        mTaskList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                Task item = (Task) mCheckList.get(position);
                //盘点任务
                Intent intent = new Intent(TaskActivity.this, TaskDetailActivity.class);
                intent.putExtra("id", item.getId());
                intent.putExtra("beginTime", item.getLast_task());
                intent.putExtra("name", item.getName());
                startActivity(intent);
            }
        });
    }

    private void requestFinishPatrol(final int position) {
        Patrol patrol = (Patrol) mPatrolList.get(position);
        HttpClient client = new HttpClient(TaskActivity.this);
        Call call = client.service().finishPatrol(patrol.getPatrol_id());
        client.request(call, new ResponseHandler<ResponseBody>() {
            @Override
            public void onSuccess(ResponseBody patrolList) {
                showDialog.dismiss();
                MessagePop.ToastMessage(TaskActivity.this, "任务完成");
                mNormalTaskAdapter.removeItem(position);
            }

            @Override
            public void onFailure(int code, Error e) {
                showDialog.dismiss();
                if (code != 404) {
                    MessagePop.ToastMessage(TaskActivity.this, e.getMessage());
                } else {
                    MessagePop.ToastMessage(TaskActivity.this, "网络异常");
                }

            }
        });
    }

    private void updatePatrolList(List dataSource) {
        mPatrolList = new ArrayList<>();
        mPatrolList.addAll(dataSource);
        mNormalTaskAdapter = new NormalTaskAdapter(mPatrolList, this);
        mNormaList.setAdapter(mNormalTaskAdapter);
        mNormaList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final int index = position;
                MaterialDialog logoutDialog = new MaterialDialog.Builder(TaskActivity.this)
                        .title("解决任务").negativeText("取消").positiveText("解决").onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                requestFinishPatrol(index);
                            }
                        }).onNegative(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                            }
                        }).show();
            }
        });
    }

    private void requestNormalTask() {
        HttpClient client = new HttpClient(TaskActivity.this);
        Call call = client.service().patrolList();
        client.request(call, new ResponseHandler<List<Patrol>>() {
            @Override
            public void onSuccess(List<Patrol> patrolList) {
                showDialog.dismiss();
                updatePatrolList(patrolList);
            }

            @Override
            public void onFailure(int code, Error e) {
                showDialog.dismiss();
                if (code != 404) {
                    MessagePop.ToastMessage(TaskActivity.this, e.getMessage());
                } else {
                    MessagePop.ToastMessage(TaskActivity.this, "网络异常");
                }

            }
        });
    }

    private void requestCheckTask() {
        HttpClient client = new HttpClient(TaskActivity.this);
        Call call = client.service().taskList();
        client.request(call, new ResponseHandler<List<Task>>() {
            @Override
            public void onSuccess(List<Task> taskList) {
                showDialog.dismiss();
                updateCheckList(taskList);
            }

            @Override
            public void onFailure(int code, Error e) {
                showDialog.dismiss();
                if (code != 404) {
                    MessagePop.ToastMessage(TaskActivity.this, e.getMessage());
                } else {
                    MessagePop.ToastMessage(TaskActivity.this, "网络异常");
                }

            }
        });
    }

    private void updateKeepList(List dataSource) {
        mKeepTaskList = new ArrayList<>();
        mKeepTaskList.addAll(dataSource);
        mKeepTaskAdapter = new KeepTaskAdapter(mKeepTaskList, this);
        mKeepList.setAdapter(mKeepTaskAdapter);
        mKeepList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final int index = position;
                final KeepTask task =(KeepTask) mKeepTaskList.get(position);
                Intent intent = new Intent(TaskActivity.this, KeepActivity.class);
                intent.putExtra("device",task);
                intent.putExtra("selectIndex",String.valueOf(index));
                startActivityForResult(intent, 20);

            }
        });
    }

    private void requestKeepTask() {
        HttpClient client = new HttpClient(TaskActivity.this);
        Call call = client.service().keepTaskList();
        client.request(call, new ResponseHandler<List<KeepTask>>() {
            @Override
            public void onSuccess(List<KeepTask> taskList) {
                showDialog.dismiss();
                updateKeepList(taskList);
            }

            @Override
            public void onFailure(int code, Error e) {
                showDialog.dismiss();
                if (code != 404) {
                    MessagePop.ToastMessage(TaskActivity.this, e.getMessage());
                } else {
                    MessagePop.ToastMessage(TaskActivity.this, "网络异常");
                }

            }
        });
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //可以根据多个请求代码来作相应的操作
        if (20 == resultCode) {
            int selectIndex = Integer.parseInt(data.getStringExtra("selectIndex"))  ;
            mKeepTaskAdapter.removeItem(selectIndex);
        }
    }
}
